//
//  HeartModel.m
//  project
//
//  Created by 黄建华 on 2018/2/6.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "HeartModel.h"
//**************************************************心率模型**********************************************
@implementation heartSubModel
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

@end

@implementation HeartModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _user_id    = SN_USER.user_id;
        _dateString = [[NSDate date] dateToDayString];
        _heartAve   = 0;
        _heartMax   = 0;
        _heartMin   = 0;
        _weekCount  = [NSDate getDaysWeekNumberWithSelectDate:[NSDate date]];
        _monthCount = [NSDate getDaysMonthNumberWithSelectDate:[NSDate date]];
        _dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:0];
        _dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:1];
        _yearCount  = [NSDate getDaysYearNumberWithSelectDate:[NSDate date] withType:2];
    }
    return self;
}

+ (HeartModel *)initWithDate:(NSDate *)date {
    HeartModel *model = [[HeartModel alloc] init];
    
    model.dateString = [date dateToDayString];
    model.user_id    = SN_USER.user_id;
    model.heartAve   = 0;
    model.heartMax   = 0;
    model.heartMin   = 0;
    model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    return model;
}

+ (HeartModel *)getHeartModelFromDB {
    HeartModel *model = [HeartModel getHeartModelFromDBWith:[NSDate date]];
    
    return model;
}

+ (HeartModel *)getHeartModelFromDBWithDayString:(NSString *)string {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, string];
    HeartModel *model = [HeartModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model            = [[HeartModel alloc] init];
        model.dateString = string;
        model.user_id    = SN_USER.user_id;
        NSDate *date = [NSDate dateByString:string];
        model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
        model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
        model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
        model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
        model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
        [model updateToDB];
    }
    return model;
}

+ (HeartModel *)getHeartModelFromDBWith:(NSDate *)date {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, [date dateToDayString]];
    HeartModel *model = [HeartModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model = [HeartModel pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    return model;
}

- (void)updateToDBSafely {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, self.dateString];
    HeartModel *model = [HeartModel searchSingleWithWhere:where orderBy:nil];
    
    if (model) {
        [HeartModel updateToDB:self where:nil];
    }
}

+ (HeartModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    HeartModel *model = [HeartModel initWithDate:date];
    
    [HeartModel creatEmptyDataArrayWithModel:model];
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    [model saveToDB];
    return model;
}

// 为模型创建空值的对象
+ (void)creatEmptyDataArrayWithModel:(HeartModel *)model {
}

// 表名
+ (NSString *)getTableName {
    return @"HeartModel";
}

// 复合主键
+ (NSArray *)getPrimaryKeyUnionArray {
    return @[@"user_id", @"dateString"];
}

// 表版本
+ (int)getTableVersion {
    return 1;
}

+ (void)initialize {
    [super initialize];
    
    [self bindYYJSONKey:@"min" toProperty:@"heartMin"];
    [self bindYYJSONKey:@"max" toProperty:@"heartMax"];
    [self bindYYJSONKey:@"average" toProperty:@"heartAve"];
    [self bindYYJSONKey:@"data" toProperty:@"detailData"];
    [self bindYYJSONKey:@"date" toProperty:@"dateString"];
    
    [self removePropertyWithColumnName:@"detailData"];
}

- (void)updateRealHeartData:(NSInteger)data {
    [SN_PublicClass.heartCheckArray addObject:StrByInt(data)];
    SN_PublicClass.heartValueString = StrByInt(data);
    if (SN_PublicClass.heartBlock) {
        SN_PublicClass.heartBlock(data);
    }
}

- (void)updateRealHeartDataEnd:(NSArray *)heartArray {
    NSLog(@"updateRealHeartDataEnd: >>>>>%@", heartArray);
    
    SN_PublicClass.heartCheckArray = [NSMutableArray array];
    [SN_PublicClass.heartCheckArray addObjectsFromArray:heartArray];
    
    int             total  = 0;
    NSMutableString *DataS = [NSMutableString string];
    for (NSString *heartS in SN_PublicClass.heartCheckArray) {
        total += heartS.intValue;
        [DataS appendString:heartS];
        [DataS appendString:@","];
    }
    heartSubModel *heartModel = [[heartSubModel alloc] init];
    heartModel.heartValue = total / SN_PublicClass.heartCheckArray.count;
    heartModel.count      = [NSDate getCurrentMinTotal]/15;
    int currentMin = [NSDate getCurrentMinTotal];
    heartModel.countMins = currentMin;
    NSDate *nowDate      = [NSDate date];//现在的UTC时间也可以写成[[NSDate alloc] init];
    NSDate *startOfToday = [[NSCalendar currentCalendar] startOfDayForDate:nowDate];
    
    NSDate   *date = [startOfToday dateByAddingTimeInterval:currentMin *60];
    NSString *time = [date dateToStringHourMin];
    heartModel.updateTime = time;
    //            heartModel.data = DataS;
    
    HeartModel     *tmodel     = SN_PublicClass.todayHeart;
    NSMutableArray *checkArray = [NSMutableArray arrayWithArray:tmodel.heartSuArrayCheck];
    [checkArray addObject:heartModel];
    tmodel.heartSuArrayCheck = [NSMutableArray arrayWithArray:checkArray];
    [tmodel updateToDB];
}

// 心率大数据
+ (void)updateHeartData:(NSData *)heartData {
    UInt8 val[20] = {0};
    
    [heartData getBytes:&val length:heartData.length];
    NSString *content = [NSString stringWithFormat:@"%@", heartData];
    if (val[3] == 0) {
        SN_PublicClass.todayHeartArray = [NSMutableArray array];
        LogWrite(@"今日心率大数据", content, nil);
    } else if (val[3] == 6) {
        SN_PublicClass.yesHeartArray = [NSMutableArray array];
        LogWrite(@"昨日心率大数据", content, nil);
    } else {
        LogWrite(nil, content, nil);
    }
    
    if (val[3] < 6) {
        for (int i = 4; i < 20; i++) {
            NSString *heart = [NSString stringWithFormat:@"%d", val[i]];
            if (heart.integerValue != 0 && (heart.integerValue <= 55 || heart.integerValue >= 200)) {
                LogWrite(@"今日心率", heart, @"异常");
                ErrorTimes++;
                [[NSUserDefaults standardUserDefaults] setInteger:ErrorTimes forKey:[NSDate date].dateToDayString];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            [SN_PublicClass.todayHeartArray addObject:heart];
        }
    } else if (val[3] < 12) {
        for (int i = 4; i < 20; i++) {
            NSString *heart = [NSString stringWithFormat:@"%d", val[i]];
            if (heart.integerValue != 0 && (heart.integerValue <= 55 || heart.integerValue >= 200)) {
                LogWrite(@"昨日心率", heart, @"异常");
                ErrorTimes++;
                [[NSUserDefaults standardUserDefaults] setInteger:ErrorTimes forKey:[NSDate date].dateToDayString];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            [SN_PublicClass.yesHeartArray addObject:heart];
        }
    }
}

+ (void)heartTransEnd {
    [HeartModel updateHeartYes];
    [HeartModel updateHeartToday];
    if ([[NSString stringWithFormat:@"%@",SN_USER.user_id] getBOOLValue]) {
        [SN_Net updateEveryModelWithType:HJUpdateHeart];
        
    }
    LogWrite(nil, nil, @"心率大数据同步完成");
    NSLog(@"心率数据同步完成>>>");
}

+ (void)updateHeartToday {
    // 今天心率
    HeartModel     *tmodel          = SN_PublicClass.todayHeart;
    NSArray        *theartArray     = [NSArray arrayWithArray:SN_PublicClass.todayHeartArray];
    NSMutableArray *theartAutoArray = [NSMutableArray array];
    
    for (int i = 0; i < theartArray.count; i++) {
        NSInteger heartValue = [[theartArray objectAtIndex:i]integerValue];
        SN_PublicClass.hearSubModel            = [[heartSubModel alloc] init];
        SN_PublicClass.hearSubModel.count      = i;
        SN_PublicClass.hearSubModel.heartValue = heartValue;
        NSDate   *nowDate      = [NSDate date];//现在的UTC时间也可以写成[[NSDate alloc] init];
        NSDate   *startOfToday = [[NSCalendar currentCalendar] startOfDayForDate:nowDate];
        NSDate   *date         = [startOfToday dateByAddingTimeInterval:i *900];
        NSString *time         = [date dateToStringHourMin];
        SN_PublicClass.hearSubModel.countMins  = i *15;
        SN_PublicClass.hearSubModel.updateTime = time;
        if (heartValue >=55) {
            [theartAutoArray addObject:SN_PublicClass.hearSubModel];
        }
    }
    tmodel.heartsuArrayAuto = [NSMutableArray arrayWithArray:theartAutoArray];
    
    // 手动 自动排序 计算详情
    NSMutableArray *allModelArray     = [NSMutableArray array];
    NSMutableArray *heartAuto         = [NSMutableArray arrayWithArray:tmodel.heartsuArrayAuto];
    NSMutableArray *heartCheck        = [NSMutableArray arrayWithArray:tmodel.heartSuArrayCheck];
    [allModelArray addObjectsFromArray:heartAuto];
    [allModelArray addObjectsFromArray:heartCheck];

    NSArray *sortedArray = [allModelArray sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        heartSubModel *heartModel1 = (heartSubModel *)obj1;
        heartSubModel *heartModel2 = (heartSubModel *)obj2;
        return [@(heartModel1.count) compare:@(heartModel2.count)];
    }];
    
    NSMutableArray *timeArray  = [NSMutableArray array];
    NSMutableArray *valueArray = [NSMutableArray array];
    for (int i = 0; i < sortedArray.count; i++) {
        heartSubModel *hModel = [sortedArray objectAtIndex:i];
        if (hModel.heartValue >= 55) {
            [valueArray addObject:StrByInt(hModel.heartValue)];
            [timeArray addObject:[hModel.updateTime componentsSeparatedByString:@" "][1]];
        }
    }
    
    tmodel.heartAllTimeArray  = [NSArray arrayWithArray:timeArray];
    tmodel.heartAllValueArray = [NSArray arrayWithArray:valueArray];
    
    NSMutableArray *heartValueArray48 = [NSMutableArray array];
    for (int i = 0; i < 96; i++) {
        [heartValueArray48 addObject:@"0"];
    }
    
    for (int i = 0; i < heartAuto.count; i++) {
        heartSubModel *hheartModel = [heartAuto objectAtIndex:i];
        int           aveValue     = 0;
        for (int k = 0; k < heartValueArray48.count; k++) {
            if (hheartModel.count == k) {
                if (hheartModel.heartValue >= 55) {
                    aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                    [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                }
            }
        }
    }
    
    for (int i = 0; i < heartCheck.count; i++) {
        heartSubModel *hheartModel = [heartCheck objectAtIndex:i];
        int           aveValue     = 0;
        for (int k = 0; k < heartValueArray48.count; k++) {
            if (hheartModel.count == k) {
                 if (hheartModel.heartValue >= 55) {
                aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                 }
            }
        }
    }
    tmodel.heartChartArray = [NSArray arrayWithArray:heartValueArray48];
    int heartave   = 0;
    int heartCount = 0;
    for (NSString *sss in heartValueArray48) {
        if (sss.integerValue >= 55) {
            heartave += sss.integerValue;
            heartCount++;
        }
    }
    CGFloat maxValue = [[valueArray valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat minValue = [[valueArray valueForKeyPath:@"@min.floatValue"] floatValue];
    tmodel.heartMax = maxValue;
    tmodel.heartMin = minValue;
    tmodel.heartAve = heartave / heartCount;
    [tmodel updateToDB];
}

+ (void)updateHeartYes {
    // 昨天心率
    HeartModel     *tmodel          = SN_PublicClass.yesHeart;
    NSArray        *theartArray     = [NSArray arrayWithArray:SN_PublicClass.yesHeartArray];
    NSMutableArray *theartAutoArray = [NSMutableArray array];
    
    for (int i = 0; i < theartArray.count; i++) {
        NSInteger heartValue = [[theartArray objectAtIndex:i]integerValue];
        SN_PublicClass.hearSubModel            = [[heartSubModel alloc] init];
        SN_PublicClass.hearSubModel.count      = i;
        SN_PublicClass.hearSubModel.heartValue = heartValue;
        NSDate   *nowDate      = [NSDate date];//现在的UTC时间也可以写成[[NSDate alloc] init];
        NSDate   *startOfToday = [[NSCalendar currentCalendar] startOfDayForDate:nowDate];
        NSDate   *date         = [startOfToday dateByAddingTimeInterval:i *900];
        NSString *time         = [date dateToStringHourMin];
        SN_PublicClass.hearSubModel.countMins  = i *15;
        SN_PublicClass.hearSubModel.updateTime = time;
        if (heartValue >=55) {
         [theartAutoArray addObject:SN_PublicClass.hearSubModel];
        }
    }
    tmodel.heartsuArrayAuto = [NSMutableArray arrayWithArray:theartAutoArray];
    //    NSLog(@"tmodel.heartsuArrayAuto>>>>>%@",showValue);
    
    // 手动 自动排序 计算详情
    NSMutableArray *allModelArray     = [NSMutableArray array];
    NSMutableArray *heartAuto         = [NSMutableArray arrayWithArray:tmodel.heartsuArrayAuto];
    NSMutableArray *heartCheck        = [NSMutableArray arrayWithArray:tmodel.heartSuArrayCheck];
    [allModelArray addObjectsFromArray:heartAuto];
    [allModelArray addObjectsFromArray:heartCheck];
    
    NSArray *sortedArray = [allModelArray sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        heartSubModel *heartModel1 = (heartSubModel *)obj1;
        heartSubModel *heartModel2 = (heartSubModel *)obj2;
        return [@(heartModel1.count) compare:@(heartModel2.count)];
    }];
    
    NSMutableArray *timeArray  = [NSMutableArray array];
    NSMutableArray *valueArray = [NSMutableArray array];
    for (int i = 0; i < sortedArray.count; i++) {
        heartSubModel *hModel = [sortedArray objectAtIndex:i];
        if (hModel.heartValue > 55) {
            [valueArray addObject:StrByInt(hModel.heartValue)];
            [timeArray addObject:[hModel.updateTime componentsSeparatedByString:@" "][1]];
        }
    }
    tmodel.heartAllTimeArray  = [NSArray arrayWithArray:timeArray];
    tmodel.heartAllValueArray = [NSArray arrayWithArray:valueArray];
    
    NSMutableArray *heartValueArray48 = [NSMutableArray array];
    for (int i = 0; i < 96; i++) {
        [heartValueArray48 addObject:@"0"];
    }
    
    for (int i = 0; i < heartAuto.count; i++) {
        heartSubModel *hheartModel = [heartAuto objectAtIndex:i];
        int           aveValue     = 0;
        for (int k = 0; k < heartValueArray48.count; k++) {
            if (hheartModel.count == k) {
                 if (hheartModel.heartValue >= 55) {
                aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                 }
            }
        }
    }
    
    for (int i = 0; i < heartCheck.count; i++) {
        heartSubModel *hheartModel = [heartCheck objectAtIndex:i];
        int           aveValue     = 0;
        for (int k = 0; k < heartValueArray48.count; k++) {
            if (hheartModel.count == k) {
                 if (hheartModel.heartValue >= 55) {
                aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                 }
            }
        }
    }
    tmodel.heartChartArray = [NSArray arrayWithArray:heartValueArray48];
    int heartave   = 0;
    int heartCount = 0;
    for (NSString *sss in heartValueArray48) {
        if (sss.integerValue >= 55) {
            heartave += sss.integerValue;
            heartCount++;
        }
    }
    
    CGFloat maxValue = [[valueArray valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat minValue = [[valueArray valueForKeyPath:@"@min.floatValue"] floatValue];
    tmodel.heartMax = maxValue;
    tmodel.heartMin = minValue;
    tmodel.heartAve = heartave / heartCount;
    [tmodel updateToDB];
}

+ (void)updateCheckHeart {
    // 今天心率
    HeartModel *tmodel = SN_PublicClass.todayHeart;
    // 手动 自动排序 计算详情
    NSMutableArray *allModelArray     = [NSMutableArray array];
    NSMutableArray *heartAuto         = [NSMutableArray arrayWithArray:tmodel.heartsuArrayAuto];
    NSMutableArray *heartCheck        = [NSMutableArray arrayWithArray:tmodel.heartSuArrayCheck];
    [allModelArray addObjectsFromArray:heartAuto];
    [allModelArray addObjectsFromArray:heartCheck];
    
    NSArray *sortedArray = [allModelArray sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        heartSubModel *heartModel1 = (heartSubModel *)obj1;
        heartSubModel *heartModel2 = (heartSubModel *)obj2;
        return [@(heartModel1.count) compare:@(heartModel2.count)];
    }];
    
    NSMutableArray *timeArray  = [NSMutableArray array];
    NSMutableArray *valueArray = [NSMutableArray array];
    for (int i = 0; i < sortedArray.count; i++) {
        heartSubModel *hModel = [sortedArray objectAtIndex:i];
        if (hModel.heartValue >= 55) {
            [valueArray addObject:StrByInt(hModel.heartValue)];
            [timeArray addObject:[hModel.updateTime componentsSeparatedByString:@" "][1]];
        }
    }
    tmodel.heartAllTimeArray  = [NSArray arrayWithArray:timeArray];
    tmodel.heartAllValueArray = [NSArray arrayWithArray:valueArray];
    
    NSMutableArray *heartValueArray48 = [NSMutableArray array];
    for (int i = 0; i < 96; i++) {
        [heartValueArray48 addObject:@"0"];
    }
    
    for (int i = 0; i < heartAuto.count; i++) {
        heartSubModel *hheartModel = [heartAuto objectAtIndex:i];
        int           aveValue     = 0;
        for (int k = 0; k < heartValueArray48.count; k++) {
            if (hheartModel.count == k) {
                 if (hheartModel.heartValue >= 55) {
                aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                 }
            }
        }
    }
    
    for (int i = 0; i < heartCheck.count; i++) {
        heartSubModel *hheartModel = [heartCheck objectAtIndex:i];
        int           aveValue     = 0;
        for (int k = 0; k < heartValueArray48.count; k++) {
            if (hheartModel.count == k) {
                 if (hheartModel.heartValue >= 55) {
                aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                 }
            }
        }
    }
    tmodel.heartChartArray = [NSArray arrayWithArray:heartValueArray48];
    int heartave   = 0;
    int heartCount = 0;
    for (NSString *sss in heartValueArray48) {
        if (sss.integerValue >= 55) {
            heartave += sss.integerValue;
            heartCount++;
        }
    }
    
    CGFloat maxValue = [[valueArray valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat minValue = [[valueArray valueForKeyPath:@"@min.floatValue"] floatValue];
    tmodel.heartMax = maxValue;
    tmodel.heartMin = minValue;
    tmodel.heartAve = heartave / heartCount;
    [tmodel updateToDB];
    NSLog(@"手动检测心率数据同步完成>>>");
    [SN_Net updateEveryModelWithType:HJUpdateHeart];
    // 回到主线程
}

//同步下载数据需要的
- (void)saveToDBByDownload {
    NSDate *date = [NSDate dateByString:self.dateString];
    self.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    self.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    self.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    self.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    self.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    NSArray *array = (NSArray *)[self.detailData parseJSONString];
    if ([array isKindOfClass:NSArray.class] && array.count > 0) {
        self.heartsuArrayAuto = [NSMutableArray array];
        self.heartSuArrayCheck = [NSMutableArray array];
        NSMutableArray *heartAllTimeArray  = [NSMutableArray array];
        NSMutableArray *heartAllValueArray = [NSMutableArray array];
        for (int i = 0; i < array.count; i++) {
            NSDictionary *dict = array[i];
            if ([dict isKindOfClass:NSDictionary.class]) {
                if (dict[@"value"] && dict[@"time"] && [dict[@"value"] integerValue]>=55) {
                    heartSubModel *model = [[heartSubModel alloc] init];
                    model.heartValue = [dict[@"value"] integerValue];
                    NSString *time       = @"";
                    NSArray  *timeArrayS = [dict[@"time"] componentsSeparatedByString:@" "];
                    if (timeArrayS.count == 2) {
                        model.updateTime = dict[@"time"];
                        time             = [timeArrayS lastObject];
                    } else {
                        NSString *updateTimeString = [NSString stringWithFormat:@"%@ %@", self.dateString, dict[@"time"]];
                        model.updateTime = updateTimeString;
                        time             = dict[@"time"];
                    }
                    
                    NSString *timeS     = time;
                    NSString *timeSS = @"";
                    if (timeS.length >=5) {
                        timeSS = [timeS substringWithRange:NSMakeRange(0, 5)];
                    }
                    else
                    {
                        timeSS = [timeS substringWithRange:NSMakeRange(0, timeS.length)];
                    }
                    NSArray  *timeArray = [timeSS componentsSeparatedByString:@":"];
                    int      timeInt    = [[timeArray firstObject]intValue]*60 +[[timeArray lastObject]intValue];
                    model.count     = timeInt/15;
                    model.countMins = timeInt;
                    NSString *typeString = dict[@"type"];
                    
                    if (typeString) {
                        if (typeString.integerValue == 1) {
                            [self.heartsuArrayAuto addObject:model];
                        } else {
                            [self.heartSuArrayCheck addObject:model];
                        }
                    } else {
                        [self.heartsuArrayAuto addObject:model];
                    }
                    [heartAllTimeArray addObject:time];
                    [heartAllValueArray addObject:dict[@"value"]];
                }
            }
        }
        
        //        NSLog(@"心率自动>>>>%@",self.heartsuArrayAuto);
        //        NSLog(@"心率手动>>>>%@",self.heartsuArrayAuto);
        
        NSMutableArray *allModelArray = [NSMutableArray array];
        NSMutableArray *heartAuto     = [NSMutableArray arrayWithArray:self.heartsuArrayAuto];
        NSMutableArray *heartCheck    = [NSMutableArray arrayWithArray:self.heartSuArrayCheck];
        [allModelArray addObjectsFromArray:heartAuto];
        [allModelArray addObjectsFromArray:heartCheck];
        
        
        NSMutableArray *heartValueArray48 = [NSMutableArray array];
        for (int i = 0; i < 96; i++) {
            [heartValueArray48 addObject:@"0"];
        }
        
        for (int i = 0; i < heartAuto.count; i++) {
            heartSubModel *hheartModel = [heartAuto objectAtIndex:i];
            int           aveValue     = 0;
            for (int k = 0; k < heartValueArray48.count; k++) {
                if (hheartModel.count == k) {
                    if (hheartModel.heartValue >=55) {
                        aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                        [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                    }
                }
            }
        }
        
        for (int i = 0; i < heartCheck.count; i++) {
            heartSubModel *hheartModel = [heartCheck objectAtIndex:i];
            int           aveValue     = 0;
            for (int k = 0; k < heartValueArray48.count; k++) {
                if (hheartModel.count == k) {
                 if (hheartModel.heartValue >=55) {
                    aveValue = hheartModel.heartValue + [[heartValueArray48 objectAtIndex:k]integerValue] /2;
                    [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                 }
                }
            }
        }
        int heartave   = 0;
        int heartCount = 0;
        for (NSString *sss in heartValueArray48) {
            if (sss.integerValue >= 55) {
                heartave += sss.integerValue;
                heartCount++;
            }
        }
        CGFloat maxValue = [[heartAllValueArray valueForKeyPath:@"@max.floatValue"] floatValue];
        CGFloat minValue = [[heartAllValueArray valueForKeyPath:@"@min.floatValue"] floatValue];
        self.heartMax           = maxValue;
        self.heartMin           = minValue;
        self.heartAve           = heartave / heartCount;
        self.heartChartArray    = [NSArray arrayWithArray:heartValueArray48];
        self.heartAllTimeArray  = [NSArray arrayWithArray:heartAllTimeArray];
        self.heartAllValueArray = [NSArray arrayWithArray:heartAllValueArray];
        
    }
    
    NSString *todayStr = [[NSDate date] dateToDayString];
    if (self.dateString != todayStr) {
        self.isSaveAllDay = YES;
    }
    
    if ([self.dateString isEqualToString:[[NSDate date]dateToDayString]]) {
        NSString *saveKey = [NSString stringWithFormat:@"%@",SN_USER.user_id];
        [saveKey setBOOLValue:YES];
    }
    
    [self updateToDB];
}

@end

